package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	g "gogame/game"
	"gogame/game/module"
	"gogame/gameconfig"
	"gogame/gameservice"
	_ "gogame/gameservice/gateway"
	_ "gogame/gameservice/modellog"
	_ "gogame/gameservice/timer"
	_ "gogame/gameservice/worker"
	"gogame/lib"
	"time"
)

/*
	服务启动
*/

var StartCmd = &cobra.Command{
	Use:  "start",
	Long: "start 服务名...(不指定服务名默认开启所有)",
	Run:  Start,
}

func init() {
	RootCmd.AddCommand(StartCmd)

}

func Start(cmd *cobra.Command, startServiceNames []string) {
	_startServiceNames := []string{"all"}
	if len(startServiceNames) > 0 {
		_startServiceNames = startServiceNames
	}

	// 多个命令中包含all，只留all
	if len(_startServiceNames) > 1 && lib.InSliceString("all", _startServiceNames) {
		_startServiceNames = []string{"all"}
	}

	var _errNum int
	for _, startServiceName := range _startServiceNames {
		switch startServiceName {
		case "all":
			RunAll()
		case "gateway":
			RunGateway()
		case "worker":
			gameservice.RunWorker()
		case "timer":
			gameservice.RunTimer()
		case "modellog":
			gameservice.RunModelLog()
		default:
			fmt.Printf("service name: %s not exists!!!", startServiceName)
			_errNum++
		}
	}

	// 等待所有服务结束
	if _errNum < len(_startServiceNames) {
		gameservice.WaitStop()
	}

}

func RunAll() {
	// 接口注册
	module.InitRoute()

	// 启动worker
	gameservice.RunWorker()

	time.Sleep(time.Second * 2)

	// 启动定时器
	gameservice.RunTimer()
	// 启动model_log
	gameservice.RunModelLog()

	RunGateway()

}

func RunGateway() {
	_gameVer := gameconfig.ServerConfig.GetGameVer()
	switch _gameVer {
	case "cross":
		g.CrossRedis.FlushAll()
	default:
		g.Redis.FlushAll()

		// 启动gateway
		gameservice.RunGateway()
	}
}
